
alter      procedure p_closeoffadjrate
  @curryear integer,
  @currmonth integer,
  @cokendadjrate integer,
  @succeeded integer out
as
  set nocount on
declare @moneyid integer
declare @subid integer
declare @isdebit integer
declare @voucherid integer
declare @rate decimal(18,8)
declare @amt decimal(18,2)
declare @sumamt decimal(18,2)
declare @vouyearmonth varchar(6)
declare @local_tab_adj table(subjectid integer,
                               isdebit int)
declare @local_tab_money table(moneyid integer,
                             rate double precision)
declare cur_adjust cursor for select * from @local_tab_adj
begin
  set @succeeded = 0
  set @vouyearmonth=cast(@curryear as char(4))+ right(cast(100+@currmonth as char(3)),2)
  if exists(select voucherid from tfb_voucher where vouyearmonth=@vouyearmonth and formertype=@cokendadjrate) 
  begin
    set @succeeded = 1
    deallocate cur_adjust
    return
  end
  
  set @sumamt = 0;
  insert into @local_tab_money
  select moneyid, rate from td_money where moneyid <> 0
  declare cur_money cursor for
    select * from @local_tab_money

  open cur_money
  fetch next from  cur_money
  into  @moneyid,@rate
  while @@fetch_status = 0 
  begin    
    delete from @local_tab_adj
    insert into @local_tab_adj
    select subjectid, isdebit from tfd_subject where subnode=1 and dofmoney=1 and isadjrate=1;

    open cur_adjust
    fetch next from  cur_adjust
    into  @subid,@isdebit
    while @@fetch_status = 0 
    begin    
      execute p_getadjustexchrateamt @subid,@isdebit,@moneyid,@rate,@curryear,@currmonth,-99, @amt out
      if (@isdebit=1)
          set @sumamt = @sumamt + @amt
      else
          set @sumamt = @sumamt - @amt
      fetch next from  cur_adjust
      into  @subid,@isdebit
    end
    close cur_adjust
    fetch next from  cur_money
    into  @moneyid,@rate

  end

  if(@sumamt = 0)  set @succeeded = 1

  close cur_money
  deallocate  cur_money
  deallocate  cur_adjust
end





GO
